package com.yl.mybatis.session;

import com.yl.mybatis.annotation.Select;
import com.yl.mybatis.binding.MapperMethod;
import com.yl.mybatis.binding.MapperRegistry;
import com.yl.mybatis.scanner.SimpleScanner;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: TODO
 * @author: yoozhoo
 * @modified By: yoozhoo
 * @date: Created in 2021/1/4 6:06 下午
 * @version:v1.0
 */
public class Configuration implements IConfiguration {
    private MapperRegistry mapperRegistry = new MapperRegistry();


    protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;
    @Override
    public void loadConfigurations(){
        SimpleScanner simpleScanner = new SimpleScanner("com.yl.mybatis.mapper");
        List<Class<?>> classes = simpleScanner.doScan();
        mapperRegistry.setKnownMappers(loadAnnotationConfiguration(classes));
    }


    public ExecutorType getDefaultExecutorType() {
        return defaultExecutorType;
    }

    @Override
    public MapperRegistry getMapperRegistry() {
        return mapperRegistry;
    }
    private Map<String, MapperMethod> loadAnnotationConfiguration(List<Class<?>> classes) {

        Map<String, MapperMethod> map = new HashMap<>(16);

        for (Class<?> aClass : classes) {
            for (Method method : aClass.getMethods()) {
                for (Annotation annotation : method.getAnnotations()) {
                    if (annotation instanceof Select) {
                        MapperMethod mapperModel = new MapperMethod();
                        //----获取sql
                        String sql = ((Select) annotation).value()[0];
                        mapperModel.setSql(sql.trim());
                        //获取返回值类型
                        mapperModel.setType(method.getReturnType());
                        map.put(aClass.getName() + "." + method.getName(), mapperModel);
                    }
                }
            }
        }
        return map;
    }

    public void addMapper(Class<?> type) {
        mapperRegistry.addMapper(type);
    }
}
